<template>
  <view class="home">
    <view>
      <form @submit="formSubmit">
        <view class="form">
          <view class="content paddingBotNone">
            <view class="title">与我的关系</view>
            <view
              v-if="isAddMember || formData.identity !== 1"
              :class="[identityItem.length < 4 ? 'disBlockBox textLeft' : 'disBlockBox indentContent']"
            >
              <!-- <view class="indentTitle">关系</view> -->
              <view
                v-for="item in identityItem"
                :key="item.value"
                :class="[
                  'disBlockKid',
                  !isAddMember ? 'pointNone' : null,
                  item.value === formData.identity ? 'chose' : null
                ]"
                @click="choseUser(item)"
              >
                <text :class="['disBlock']">
                  {{ item.label }}
                </text>
                <img v-show="item.value === formData.identity" class="choseImg" :src="curIcon" alt="" />
              </view>
            </view>
            <view class="inputBox">
              <view
                v-show="focusInp === 'name' && formData.name"
                class="clearInp"
                @click.native.stop="clearFun('name')"
              >
                <img :src="closeIcon" />
              </view>
              <span class="name lineHeight86 requestField">姓名</span>
              <input
                key="name"
                v-model="formData.name"
                class="uni-input lineHeight86"
                name="name"
                placeholder="请输入姓名"
                :disabled="isAuthen"
                placeholder-class="phcolor"
                @focus="vauleEmpty('name')"
                @blur="unFocus"
              />
              <!-- <view class="inputIcon" @click="vauleEmpty('name')">
                <img :src="require('./../images/icons/right.png')" />
              </view> -->
              <view class="clear"></view>
            </view>
            <view class="inputBox marginRight50">
              <span class="name lineHeight86 requestField">性别</span>
              <view :class="[isAuthen || formData.idCard ? 'sickBox pointNone' : 'sickBox']">
                <view
                  v-for="item in sexItem"
                  :key="item.value"
                  :class="[item.value === formData.sex ? 'chose sickBtn' : 'sickBtn']"
                  @click="choseSex(item.value)"
                >
                  {{ item.name }}
                  <view v-show="item.value === formData.sex" class="cur"><img :src="curIcon" /></view>
                </view>
              </view>
              <view class="clear"></view>
            </view>
            <view class="inputBox">
              <span class="name lineHeight86 requestField">生日</span>
              <view class="uni-list">
                <view class="uni-list-cell">
                  <view :class="[isAuthen || formData.idCard ? 'uni-list-cell-db pointNone' : 'uni-list-cell-db']">
                    <picker
                      class="pickStyle"
                      mode="date"
                      name="birthday"
                      :value="formData.birthday"
                      :disabled="isAuthen"
                      :start="startDate"
                      :end="endDate"
                      @focus="vauleEmpty('birthday')"
                      @change="bindDateChange"
                    >
                      <view class="uni-input">
                        <span v-if="formData.birthday">{{ formData.birthday }}</span>
                        <span v-else class="grey">请选择生日</span>
                      </view>
                      <view class="inputIcon"><img :src="require('./../images/icons/right.png')" /></view>
                    </picker>
                  </view>
                </view>
              </view>
              <view class="clear"></view>
            </view>

            <view class="inputBox messageCodeBox">
              <view
                v-show="focusInp === 'phone' && formData.phone"
                class="clearInp"
                @click.native.stop="clearFun('phone')"
              >
                <img :src="closeIcon" />
              </view>
              <span class="name lineHeight86">手机号</span>
              <label class="messageInputWith">
                <input
                  key="phone"
                  v-model="formData.phone"
                  type="number"
                  class="uni-input lineHeight86"
                  name="phone"
                  maxlength="11"
                  :disabled="!canEditPhone"
                  placeholder="请输入手机号"
                  placeholder-class="phcolor"
                  @focus="vauleEmpty('phone')"
                  @blur="unFocus"
                />
              </label>
              <view class="clear"></view>
            </view>
            <view class="inputBox">
              <view
                v-show="focusInp === 'idCard' && formData.idCard"
                class="clearInp"
                @click.native.stop="clearFun('idCard')"
              >
                <img :src="closeIcon" />
              </view>
              <span class="name lineHeight86">身份证</span>
              <input
                key="idCard"
                v-model="formData.idCard"
                type="idcard"
                class="uni-input lineHeight86"
                name="idCard"
                placeholder="请输入身份证号"
                placeholder-class="phcolor"
                maxlength="18"
                :disabled="isAuthen"
                @change="idCardChange($event, formData.idCard)"
                @focus="vauleEmpty('idCard')"
                @blur="unFocus"
              />
              <view v-show="isAuthen" class="idAuthen">实名</view>
              <view class="clear"></view>
            </view>

            <!-- <view class="inputBox messageCodeBox">
              <view v-if="focusInp === 'machineNumber'" class="clearInp" @click.native.stop="clearFun('machineNumber')">
                <img :src="closeIcon" />
              </view>
              <span class="name lineHeight86">其他号码</span>
              <label class="messageInputWith">
                <input
                  key="machineNumber"
                  v-model="formData.machineNumber"
                  class="uni-input lineHeight86"
                  name="machineNumber"
                  maxlength="20"
                  placeholder="请输入,如：010-88888888"
                  placeholder-class="phcolor"
                  @focus="vauleEmpty('machineNumber')"
                  @blur="unFocus"
                />
              </label>
              <view class="clear"></view>
            </view> -->
          </view>
        </view>
        <fixed-bottom-button v-if="isLogin">
          <view class="uni-btn-v">
            <button form-type="submit">保存</button>
          </view>
        </fixed-bottom-button>
      </form>
    </view>
  </view>
</template>
<script>
import { hospitalId, registerSource } from '@/common/baseUrl.js';
import { getPatientId } from '@/utils/auth.js';
import { getInfoByIdCard } from '@/utils/optimize.js';
import fixedBottomButton from '@/components/fixedBottomBtn';
// 引入统计
import { tongji } from '@/utils/tools.js';
import {
  getUserInfoByPatientId,
  getPatientIdByIdCard,
  sendUserInfoForm,
  bindPatients,
  addFamilyMember,
  getRealNameResult,
  getFamilyMember
} from '@/api/join.js';
import curIcon from '@/static/icon/cur.png';
import pCheckedIcon from '@/static/icon/p-checked.png';
import pNoCheckedIcon from '@/static/icon/p-nochecked.png';
import { mapState } from 'vuex';
import clearIconImg from '@/static/icon/clearIcon.png';

let graceChecker = require('../../common/graceChecker.js');
export default {
  components: {
    fixedBottomButton
  },
  data() {
    const currentDate = this.getDate({
      format: true
    });
    return {
      curIcon: curIcon,
      pCheckedIcon,
      pNoCheckedIcon,
      identityItem: [
        // {
        //   label: '本人',
        //   value: 1,
        //   click: false
        // },
        {
          label: '父母',
          value: 3,
          click: false
        },
        {
          label: '配偶',
          value: 2,
          click: false
        },
        {
          label: '子女',
          value: 4,
          click: false
        }
      ],
      historyItem: {
        spouseItem: [],
        parentItem: [],
        childrenItem: []
      },
      formData: this.$store.getters.storeFormData,
      isAuthen: false,
      canEditPhone: true,
      ownInfo: {},
      loginPatientId: getPatientId(),
      familyUserData: [],

      // 社区小程序
      isLogin: wx.getStorageSync('token') || false,
      articlePop: false,
      agree: false,
      artTitleArr: [],
      price: '',
      date: currentDate,
      sexItem: [
        {
          name: '男',
          value: 1
        },
        {
          name: '女',
          value: 0
        }
      ],
      show: true,
      idCardPhoneIdUnequal: false, // 手机号获取的patientId和身份证获取的patientId不一致
      argeeBoolean: false,
      isHavePhone: true, // 历史用户中是否已存在联系方式
      isHaveMachineNumber: '', // 历史用户中是否已存在其他联系方式
      getHistoryPid: '',
      memberId: '',
      isAddMember: false,
      focusInp: null,
      timer: null,
      timerTime: false,
      closeIcon: clearIconImg
    };
  },
  computed: {
    startDate() {
      return this.getDate('start');
    },
    endDate() {
      return this.getDate('end');
    },
    ...mapState('join', {
      serviceId: 'communityServiceId'
    })
  },
  watch: {
    'formData.idCard': {
      handler: function () {
        if (this.formData.idCard && this.formData.idCard.length < 18) {
          this.formData.sex = '';
          this.formData.birthday = '';
        } else if (this.formData.idCard && this.formData.idCard.length === 18) {
          this.formData.sex = getInfoByIdCard(this.formData.idCard, 2);
          this.formData.birthday = getInfoByIdCard(this.formData.idCard, 1);
        }
      },
      immediate: true
    },
    'formData.phone': {
      handler: function () {
        if (this.formData.phone && this.formData.phone.length === 11 && !this.formData.idCard) {
          this.initUserInfoByPhone();
        }
      }
    },
    isAuthen: {
      handler: function (newVal, oldVal) {
        if (newVal) {
          const self = this;
          setTimeout(function () {
            self.focusInp = null;
          }, 200);
          uni.hideKeyboard();
        }
      }
    }
  },
  onLoad(options) {
    if (options && options.memberId) {
      this.formData.patientId = options.memberId;
      this.memberId = options.memberId;
      this.formData.identity = Number(options.identity);
      this.isAddMember = false;
      wx.setNavigationBarTitle({
        title: '编辑成员'
      });
    } else {
      this.formData.identity = '';
      this.addUser();
      this.isAddMember = true;
    }

    this.getFamilyItem();
  },
  async onShow() {
    this.isLogin = wx.getStorageSync('token') || false; // 登录返回后数据重新拉取更新
    this.getUserData();
  },
  mounted() {},
  methods: {
    vauleEmpty(key) {
      // clearTimeout(this.timer);
      // this.timer = null;
      const self = this;
      if (this.timerTime) {
        setTimeout(function () {
          self.timerTime = !self.timerTime;
        }, 800);
        return;
      }
      console.log(key);
      this.focusInp = key;
    },
    clearFun(key) {
      const self = this;
      self.$set(self.formData, key, '');
      let data = JSON.parse(JSON.stringify(this.formData));
      data[key] = null;
      this.$nextTick(() => {
        self.formData = data;
      });
      this.$forceUpdate();
      if (key === 'idCard') {
        self.idCardChange('', '', 'clear');
      }
    },
    unFocus() {
      this.focusInp = null;
    },
    async initUserInfoByPhone() {
      const { data: patientId } = await getPatientIdByIdCard({
        phone: this.formData.phone,
        idCard: ''
      });
      if (patientId) {
        const { data: userInfo } = await getUserInfoByPatientId(patientId);
        this.initFormValue(userInfo);
      }
    },
    getDate(type) {
      const date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();

      if (type === 'start') {
        year = year - 120;
      } else if (type === 'end') {
        year = year + 0;
      }
      month = month > 9 ? month : '0' + month;
      day = day > 9 ? day : '0' + day;
      return `${year}-${month}-${day}`;
    },
    bindDateChange: function (e) {
      this.formData.birthday = e.target.value;
    },
    getUserData() {
      const self = this;
      if (!this.memberId) {
        return;
      }
      getUserInfoByPatientId(this.memberId).then((res) => {
        if (res.code === 0 && res.data) {
          self.initFormValue(res.data);
        }
      });
    },
    filterDisease(val) {
      // 匹配有没有热门疾病数据 sick
      return val.map((item) => {
        return item.id;
      });
    },
    getOwnData() {
      // 和底下分开，为了是减少一次接口请求，本人不需要即时请求
      this.initFormValue(this.ownInfo);
    },
    initFormValue(data, refer) {
      const self = this;
      data.memberName ? (self.formData.name = data.memberName) : (self.formData.name = data.name);
      self.formData.idCard = data.idCard;
      self.formData.phone = data.phone;
      this.canEditPhone = data.phone ? false : true;
      self.formData.address = data.address;
      self.getHistoryPid = data.patientId || '';
      self.formData.machineNumber = data.machineNumber || '';
      self.formData.birthday = data.birthday;
      self.formData.sex = data.sex;
      if (data.diseases && data.diseases.length > 0) {
        self.formData.diseases = self.filterDisease(data.diseases);
        self.formData.sick = 2;
      } else {
        self.formData.diseases = [];
        self.formData.sick = '';
      }
      if (data.realNameAuthenticationPassed === 1) {
        this.isAuthen = true;
      }
      data.phone ? (this.isHavePhone = data.phone) : (this.isHavePhone = false);
      data.machineNumber ? (this.isHaveMachineNumber = data.machineNumber) : (this.isHaveMachineNumber = false);
    },
    async idCardChange(e, val, isClear) {
      const self = this;
      if (isClear && this.isAuthen) {
        setTimeout(function () {
          self.formData.idCard = '';
        }, 400);
        return;
      }
      if (val && val.length === 18) {
        this.isAuthen = false;
        let patientId = await getPatientIdByIdCard({ phone: '', idCard: this.formData.idCard }).then((res) => {
          if (res.code === 0) {
            return res.data;
          } else {
            uni.showToast({ title: res.message, icon: 'none' });
          }
          return false;
        });
        if (patientId) {
          getUserInfoByPatientId(patientId).then((res) => {
            if (res.code === 0) {
              self.initFormValue(res.data, 'fromIdCardChange');
              if (res.data.realNameAuthenticationPassed && res.data.realNameAuthenticationPassed === 1) {
                self.isAuthen = true;
              }
            }
          });
        }
      } else if (val && val.length > 0) {
        uni.showToast({ title: '请输入正确的身份证号', icon: 'none' });
      }
    },
    // Monday Tuesday Wednesday Thursday Friday Saturday Sunday
    async choseUser(val) {
      console.log(23234234, val, this.formData.identity);
      let id = val.value;
      this.formData.identity = id;
    },
    addUser() {
      let temporaryIndentity = this.formData.identity;
      this.formData = {
        identity: '', // 为谁加入
        name: '', // 姓名
        idCard: '', // 身份证
        phone: '', // 手机号
        sick: '', // 是否患病
        address: { areaId: null, street: null, cityId: null, provinceId: null }, // 城市[10010, 10031]
        sex: '', // 性别
        birthday: '' // 生日
      };
      this.formData.identity = temporaryIndentity;
      this.isAuthen = false;
      this.isHavePhone = false;
      this.getHistoryPid = '';
    },
    checkRequestFun(formValue) {
      if (!this.formData.identity) {
        return '请选择服务对象的关系标签';
      }
      // 定义表单规则
      let rule = [
        {
          name: 'name',
          checkType: 'zhDecimal',
          checkRule: '1,20',
          errorMsg: '请填写正确姓名(1-20个汉字)'
        },
        {
          name: 'idCard',
          checkType: 'idcard',
          checkRule: '',
          isPassCheck: !this.formData.idCard,
          errorMsg: '请填写正确身份证号'
        },
        // {
        //   name: 'phone',
        //   checkType: 'phoneno',
        //   checkRule: '',
        //   errorMsg: '请填写正确手机号'
        // },
        // {
        //   name: 'machineNumber',
        //   checkType: 'phonenoOther',
        //   checkRule: '',
        //   isPassCheck: !this.formData.machineNumber,
        //   errorMsg: '请填写正确的其他联系方式'
        // },
        {
          name: 'sex',
          checkType: 'notnull',
          checkRule: '',
          errorMsg: '请选择性别'
        },
        {
          name: 'birthday',
          checkType: 'notnull',
          checkRule: '',
          errorMsg: '请选择生日'
        }
      ];
      // 购买人信息校验
      if (!graceChecker.check(this.formData, rule)) {
        return graceChecker.error;
      }
      return false;
    },
    // eslint-disable-next-line complexity
    async formSubmit(e) {
      // 基础校验
      if (this.checkRequestFun(e.detail.value)) {
        uni.showToast({ title: this.checkRequestFun(e.detail.value), icon: 'none' });
        return false;
      }
      uni.showToast({ title: '加载中', icon: 'loading', duration: 15000, mask: true });
      // 友盟统计
      tongji('104419e9-bcfd-4f5e-8d8c-b6b0dc0e1428');

      console.log('第一步', this.formData.patientId);
      // 实名校验等大部分情况的校验
      const checkReal = await this.checkRealFun();
      if (checkReal) {
        uni.showToast({ title: checkReal, icon: 'none' });
        return false;
      }
      // 前端校验结束
      let sendData = {
        identity: this.formData.identity,
        name: this.formData.name || undefined,
        idCard: this.formData.idCard || undefined,
        patientId: this.formData.patientId || undefined,
        address: this.formData.address || undefined,
        diseases: this.formData.diseases,
        phone: this.formData.phone || this.isHavePhone || '',
        machineNumber: this.formData.machineNumber || this.isHaveMachineNumber || '',
        sex: this.formData === 0 || this.formData ? this.formData.sex : undefined,
        birthday: this.formData.birthday || undefined
      };
      // 新添加家庭成员关系。（自己也要调用此接口，原因忘记了。）
      this.addFUser();

      await sendUserInfoForm(sendData).then((res) => {
        uni.hideToast();
        if (res.code === 0) {
          // uni.redirectTo({
          //   url: `/pagesC/familyMember/index`
          // });
          let pages = getCurrentPages();
          if (pages.length > 2) {
            let prePageUrl = pages[pages.length - 2].route;
            this.$wxPromise.navigateTo({
              url: `/${prePageUrl}?focusPatientId=${this.formData.patientId}`
            });
          } else {
            uni.navigateBack();
          }
        } else {
          uni.showToast({ title: res.message, icon: 'none' });
        }
      });
    },
    // eslint-disable-next-line complexity
    async checkRealFun() {
      let checRealUnPass = false;
      // 通过手机号获取patientId
      const { data: phonePatId } = this.formData.phone
        ? await getPatientIdByIdCard({
            phone: this.formData.phone,
            idCard: ''
          })
        : '';
      // 通过身份证号获取patientId
      const { data: idCardPatId } = this.formData.idCard
        ? await getPatientIdByIdCard({
            idCard: this.formData.idCard,
            phone: ''
          })
        : '';
      if (idCardPatId || phonePatId) {
        console.log('123');
        this.formData.patientId = idCardPatId || phonePatId;
      } else {
        console.log('456');
        this.formData.patientId = this.getHistoryPid || '';
        if (this.isAddMember) {
          this.formData.patientId = '';
        }
      }
      if (idCardPatId && phonePatId && idCardPatId !== phonePatId) {
        return '身份信息与手机信息不对应，无法保存，请修改后保存';
      }
      if (
        (idCardPatId && this.memberId && idCardPatId !== this.memberId) ||
        (phonePatId && this.memberId && phonePatId !== this.memberId)
      ) {
        return '用户信息不匹配，请确认身份信息是否正确';
      }
      console.log(this.formData.patientId);
      if (this.isAddMember && (await this.checkListoryHave())) {
        return '该关系已存在于关系组中，请勿重复添加。';
      }
      // 如果手机号和身份证都没有patientId，注册新用户
      if (!this.formData.patientId) {
        const bindPatientInfo = {
          phone: this.formData.phone,
          name: this.formData.name,
          idCard: this.formData.idCard,
          hospitalId: hospitalId,
          machineNumber: this.formData.machineNumber || (this.formData.phone ? '' : '无'), // 如果没有手机号，其他号码传无
          cid: uni.getStorageSync('cid') || '',
          source: registerSource
        };
        const { data: newUserData, code: newUserCode, message: newUserMessage } = await bindPatients(bindPatientInfo);
        if (newUserCode === 0 && newUserData) {
          this.formData.patientId = newUserData;
        } else {
          return newUserMessage || '注册新用户失败';
        }
      }
      if (this.formData.idCard) {
        await getRealNameResult({
          idCard: this.formData.idCard,
          name: this.formData.name,
          patientId: this.memberId || this.formData.patientId
        }).then((res) => {
          if (res.code !== 0) {
            checRealUnPass = '实名校验未通过，请做实名校验！';
            return checRealUnPass;
          }
        });
      }
      return checRealUnPass;
    },
    addFUser() {
      const data = {
        patientId: this.loginPatientId,
        memberId: this.formData.patientId,
        relation: this.formData.identity
      };
      addFamilyMember(data);
    },
    choseSex(id) {
      console.log(id);
      this.formData.sex = id;
    },
    addressFormatTrsf(val) {
      let item = [];
      if (Object.prototype.toString.call(val) === '[object Object]' && val.cityId) {
        item = [val.provinceId, val.cityId, val.areaId];
        return item;
      }
      return val;
    },
    async checkListoryHave() {
      let isHaveFamily = this.familyUserData.some(
        (item) =>
          (item.memberId === this.formData.patientId && item.relation !== this.formData.identity) ||
          (item.memberId === this.formData.patientId &&
            item.relation === this.formData.identity &&
            this.formData.identity !== 1)
      );
      if (
        (wx.getStorageSync('patientid') === this.formData.paitentId && this.formData.identity !== 1) ||
        isHaveFamily
      ) {
        console.log('存在', this.formData.patientId, wx.getStorageSync('patientid'));
        return '该用户已存在于关系组中，请勿重复添加。';
      }
      return false;
    },
    async getUserInfoByPatientIdFun(patientId) {
      const { data } = await getUserInfoByPatientId(patientId);
      return data;
    },
    async getFamilyItem() {
      let { data } = await getFamilyMember(this.loginPatientId);
      this.familyUserData = data;
    }
  }
};
</script>
<style>
page {
  background-color: #f4f4f4;
}
.uni-btn-v button {
  border: none !important;
}
button:after {
  border: none !important;
}
.phcolor {
  color: rgba(0, 0, 0, 0.3);
}
</style>
<style lang="scss">
@import 'style.scss';
</style>
